package com.gcu.gcutools

import android.os.Bundle
import android.os.Handler
import com.alibaba.android.arouter.launcher.ARouter
import com.gcu.common.base.BaseActivity
import com.gcu.common.navigation.AppApi
import com.gcu.gcutools.databinding.ActivityMainBinding

/**
 * 启动页Activity
 * @property mStartUpTime Long
 */
class LauncherActivity : BaseActivity<ActivityMainBinding>() {

    /**
     * 启动页展示时间
     * M start up time
     */
    private var mStartUpTime = 3000L
    private val mTimeCountHandler by lazy {
        TimeCountHandler()
    }
    private val mRunnable: Runnable by lazy {
        Runnable {
            if (mStartUpTime <= 0L) {
                ARouter.getInstance().build(AppApi.Fragment.Home.INDEX_ACTIVITY).navigation()
                finish()
            } else {
                mStartUpTime -= INTERVAL_TIME
                mBinding.jumpBtn.text = applicationContext.getString(
                    R.string.launcher_skip_text,
                    (mStartUpTime / INTERVAL_TIME).toString()
                )
                mTimeCountHandler.postDelayed(mRunnable, INTERVAL_TIME)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun initView() {
        mBinding.jumpBtn.text = applicationContext.getString(
            R.string.launcher_skip_text,
            (mStartUpTime / INTERVAL_TIME).toString()
        )
        mBinding.jumpBtn.setOnClickListener {
            ARouter.getInstance().build(AppApi.Fragment.Home.INDEX_ACTIVITY).navigation()
            finish()
        }
        mTimeCountHandler.postDelayed(mRunnable, INTERVAL_TIME)
    }

    /**
     * On destroy
     * activity销毁的时候避免内存泄漏，删除所有消息
     */
    override fun onDestroy() {
        super.onDestroy()
        mTimeCountHandler.removeCallbacksAndMessages(null)
    }

    companion object {

        const val TAG = "LauncherActivity"

        /**
         * 间隔时间
         * Interval Time
         */
        const val INTERVAL_TIME = 1000L

        /**
         * Time count handler
         * 静态内部类，避免内存泄露
         * @constructor Create empty Time count handler
         */
        internal class TimeCountHandler : Handler() {
            init {

            }
        }
    }
}